﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using WiseLinkWPF.Windows.Controls.GridView;
using CCF20Model;
using WiseLinkWPF.Windows.Controls;
using System.Collections;
using CCF20Module.DeviceState;
using WiseLink.RDS.Resource;
using CCF20Model.ModelBase;
namespace CCF20Module
{
    /// <summary>
    /// Interaction logic for InStock.xaml
    /// </summary>
    public partial class InStock
    {
        VehicleMaintenanceModel vrm;
        DeviceHandler deviceHandler;
        private CollectionViewSource CustomerLookupView;

        public InStock()
        {
            InitializeComponent();
            vrm = base.vrmModel;
            this.DataContext = new InstockViewModel();
        }

        
        private void radGridView1_AddingNewDataItem(object sender, WiseLinkWPF.Windows.Controls.GridView.GridViewAddingNewEventArgs e)
        {
            e.NewObject = new Device();
        }

        private void radGridView1_RowEditEnded(object sender, WiseLinkWPF.Windows.Controls.GridViewRowEditEndedEventArgs e)
        {
            if (e.EditAction == GridViewEditAction.Commit || e.EditOperationType == GridViewEditOperationType.Edit)
            {
                Device device = e.EditedItem as Device;

                if (device != null && !string.IsNullOrEmpty(device.DeviceKey))
                {
                    if (deviceModel.IsDuplicateDevice(device.IDCSimNumber, "IDCSimNum", device.DeviceID))
                    {
                        Utility.ShowMessageBox(string.Format(Message.DupliateIDCNumber, device.IDCSimNumber));
                        this.radGridView1.CancelEdit();
                        ((IList)this.radGridView1.ItemsSource).Remove(device);
                        return;
                    }
                    else if (deviceModel.IsDuplicateDevice(device.DeviceKey, "DeviceKey", device.DeviceID))
                    {
                        Utility.ShowMessageBox(string.Format(Message.DuplicateDeviceSerialNumber, device.DeviceKey));
                        this.radGridView1.CancelEdit();
                        ((IList)this.radGridView1.ItemsSource).Remove(device);
                        return;
                    }
                    else if (deviceModel.IsDuplicateDevice(device.DeviceKey, "SimCard", device.DeviceID))
                    {
                        Utility.ShowMessageBox(string.Format(Message.DuplicateSIMNumber, device.SimCard));
                        this.radGridView1.CancelEdit();
                        ((IList)this.radGridView1.ItemsSource).Remove(device);
                        return;
                    }
                    else
                    {
                        if (device.IsManual == true)
                        {
                            
                            string deviceType, idc, simCard;

                            //if (!ccfZIC.AddSalesList(device.DeviceKey, out deviceType, out simCard, out idc))
                            //{
                            //    Utility.ShowMessageBox(Message.InStockVerifyFailed);
                            //    //Device selectedDevice = radGridView1.SelectedItem as Device;

                            //    //if (selectedDevice != null)
                            //    //{
                            //    //    ((IList)this.radGridView1.ItemsSource).Remove(selectedDevice);
                            //    //}
                            //    this.radGridView1.CancelEdit();
                            //    return;
                            //}
                            //else
                            //{
                            //    device.DeviceType = deviceType;
                            //    device.IDCSimNumber = idc;
                            //    device.SimCard = simCard;
                            //    deviceModel.Update();
                            //}
                        }

                    }
                }
                else
                {
                    if (device != null)
                    {
                        ((IList)this.radGridView1.ItemsSource).Remove(device);
                        this.radGridView1.CancelEdit();
                        Utility.ShowMessageBox(Message.DeviceSerialNumberIsEmpty);
                    }

                }
            }
            else if (e.EditOperationType == GridViewEditOperationType.Insert)
            {

            }
        }

        private void Instock_Add_Click(object sender, RoutedEventArgs e)
        {
            if (this.radGridView1.RowInEditMode != null)
            {
                //this.radGridView1.RowInEditMode.CommitEdit();
                this.radGridView1.CancelEdit();
            }
            string strAction = ((Button)sender).Name;

            Device selectedDevice = radGridView1.SelectedItem as Device;

            if (selectedDevice != null)
            {
                ProcessSelectedDevice(strAction, selectedDevice);
            }
            else
            {
                ProcessUnSelectedDevice(strAction);
            }

        }

        private void ProcessUnSelectedDevice(string strAction)
        {
            switch (strAction)
            {
                case "Instock_Add"://"手动入库":
                    Device device = new Device();
                    ((IList)this.radGridView1.ItemsSource).Add(device);
                    this.radDataPager1.MoveToLastPage();
                    this.radGridView1.Items.MoveCurrentToLast();
                    break;

                case "Instock_Ship"://"发货入库":
                    this.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        //InitializeZIC().GetFHList();
                        this.radGridView1.ItemsSource = deviceModel.GetDevice();
                    }));
                    break;
                case "Instock_Print"://"打印":
                    MyPrint myPrint = new MyPrint();
                    myPrint.MySource = this.radGridView1;
                    myPrint.PrintPreview();
                    myPrint.Show();
                    break;
                case "Instock_ChoseColumn"://"列选项":
                    ChoseColumn myColumn = new ChoseColumn(null, this.radGridView1, "Device");
                    myColumn.ShowDialog();
                    break;
                case "Instock_Refresh"://"刷新":
                    LoadData();
                    break;
                case "Instock_Exchange"://"换货":
                    if (this.groupNew.Visibility == System.Windows.Visibility.Visible)
                    {
                        this.groupNew.Visibility = System.Windows.Visibility.Collapsed;
                    }
                    else
                    {
                        this.groupNew.Visibility = System.Windows.Visibility.Visible;
                    }
                    break;
            }
        }

        private void ProcessSelectedDevice(string strAction, Device selectedDevice)
        {
            switch (strAction)
            {
                case "Instock_Refresh"://"刷新":
                    LoadData();
                    break;
                case "Instock_Delete"://"删除":
                    deviceHandler.DeleteDevice();
                    break;

                case "Instock_Add"://"手动入库":
                    Device device = new Device();
                    device.DeviceType = selectedDevice.DeviceType;
                    device.DeviceKey = selectedDevice.DeviceKey;
                    ((IList)this.radGridView1.ItemsSource).Add(device);
                    this.radDataPager1.MoveToLastPage();
                    this.radGridView1.Items.MoveCurrentToLast();
                    return;
                case "Instock_Sale"://"售出":
                    SimpleCustomerInfo sci = (SimpleCustomerInfo)this.CustomerLookupComboBox.SelectedValue;
                    if (sci == null)
                    {
                        Utility.ShowMessageBox(Message.CustomerNotSelected);
                        return;
                    }

                    deviceHandler.SellToCustomer(sci.ID);

                    break;
                case "Instock_Return"://"归库":
                    deviceHandler.InStock();

                    break;

                case "Instock_Deliver"://"到货入库":
                    deviceHandler.InStock();
                    break;

                case "Instock_Register":
                    if (this.groupRegister.Visibility == System.Windows.Visibility.Visible)
                    {
                        this.groupRegister.Visibility = System.Windows.Visibility.Collapsed;
                    }
                    else
                    {
                        IDSCombo.ItemsSource = vrm.GetIDSByCity();
                        this.groupRegister.Visibility = System.Windows.Visibility.Visible;
                    }
                    break;
                case "Instock_RegisterSubmit"://"注册IDC":
                    if (selectedDevice.IsRegistered == true)
                    {
                        deviceHandler.UnRegisterIDC();
                    }
                    else
                    {
                        DropDownItem currentIDS = (DropDownItem)this.IDSCombo.SelectedItem;
                        deviceHandler.RegisterIDC(
                                        this.txtSNKey.Text.Trim(),
                                        txtSNPwd.Text.Trim(),
                                        currentIDS.name,
                                        currentIDS.value.ToString());
                    }
                    break;
                case "Instock_SpecialIDC"://"特殊IDC":
                    if (selectedDevice.IsSpecialIDC == true)
                    {
                        deviceHandler.UnRegisterSpecialIDC();
                    }
                    else
                    {
                        deviceHandler.RegisterSpecialIDC();
                    }
                    break;

                case "Instock_Refund"://"退货":

                    deviceHandler.ReturnDevice();
                    break;
                case "Instock_Repair"://"维修":

                    if (selectedDevice.DeviceStatus != DeviceStatus.Repair)
                    {
                        deviceHandler.RepairStart();
                    }
                    else
                    {
                        deviceHandler.RepairEnd();
                    }
                    break;
                case "Instock_Replace"://"确认更换":

                    if (deviceHandler.ExchangeDevice(this.txtNewIDC.Text.Trim(), this.txtNewKey.Text.Trim()))
                    {
                        this.groupNew.Visibility = System.Windows.Visibility.Collapsed;
                    }
                    break;
                case "Instock_Exchange"://"换货":
                    if (this.groupNew.Visibility == System.Windows.Visibility.Visible)
                    {
                        this.groupNew.Visibility = System.Windows.Visibility.Collapsed;
                    }
                    else
                    {
                        this.groupNew.Visibility = System.Windows.Visibility.Visible;
                    }
                    break;
                
                case "Instock_Print"://"打印":
                    MyPrint myPrint = new MyPrint();
                    myPrint.MySource = this.radGridView1;
                    myPrint.PrintPreview();
                    myPrint.Show();
                    break;
            }
            this.radGridView1.Rebind();

        }

        private void radGridView1_SelectionChanged(object sender, WiseLinkWPF.Windows.Controls.SelectionChangeEventArgs e)
        {
            if (e.AddedItems.FirstOrDefault() != null)
            {
                this.radGridView1.CurrentItem = e.AddedItems.First();
                this.radGridView1.SelectedItem = this.radGridView1.CurrentItem;
                ShowMaintenanceRecord();
                deviceHandler = new DeviceHandler(deviceModel,vehicleModel, this.radGridView1.CurrentItem as Device, (IList)this.radGridView1.ItemsSource);
                LoggerHelper.LogCCF20(string.Format("Device Selection Changed. Selected Device={0}", deviceHandler.CurrentDevice.IDCSimNumber));
            }
        }

        private void ShowMaintenanceRecord()
        {
            Device deviceData = this.radGridView1.CurrentItem as Device;
            if ((deviceData != null) && (deviceData.DeviceStatus == DeviceStatus.Sold))
            {
                //CurrentVehicleID = (int)deviceData.VehicleID;
                this.radMaintenanceRecord.CancelEdit();
                this.radMaintenanceRecord.ItemsSource = vrm.GetVehicleMaintenanceRecord(deviceData.Vehicle);
                GridViewComboBoxColumn maintenanceComboColumn = (GridViewComboBoxColumn)this.radMaintenanceRecord.Columns["MaintenanceType"];
                maintenanceComboColumn.ItemsSource = vrm.GetMaintenanceTypeByVehicle(deviceData.Vehicle);
                this.radMaintenanceRecord.ShowInsertRow = true;
            }
            else
            {
                this.radMaintenanceRecord.ItemsSource = null;
                this.radMaintenanceRecord.ShowInsertRow = false;
            }
            this.radMaintenanceRecord.Rebind();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            CustomerLookupView = (CollectionViewSource)this.FindResource("CustomerLookup");
            LoadData();

        }

        private void LoadData()
        {

            if (this.groupNew.Visibility == System.Windows.Visibility.Visible)
            {
                this.groupNew.Visibility = System.Windows.Visibility.Collapsed;
            }
            customerModel.GetSimpleCustomerInfo();
            CustomerLookupView.Source = customerModel.MySimpleCustomerInfo;

            //this.radGridView1.ItemsSource = deviceModel.GetDevice();
            //this.radGridView1.Rebind();
        }

        private void radMaintenanceRecord_RowEditEnded(object sender, WiseLinkWPF.Windows.Controls.GridViewRowEditEndedEventArgs e)
        {
            if (e.EditAction == GridViewEditAction.Commit)//|| e.EditOperationType == GridViewEditOperationType.Edit)
            {
                VehicleMaintenanceRecord vmr = (VehicleMaintenanceRecord)e.EditedItem;
                if (vmr == null || vmr.MaintenanceTypeID == null)
                {
                    if (vmr != null)
                    {
                        ((IList)radMaintenanceRecord.ItemsSource).Remove(vmr);
                    }
                    e.Row.CancelEdit();

                }
                else if ((vmr.LastServiceMileage == null && vmr.LastServiceDate != null) ||
                         (vmr.LastServiceMileage != null && vmr.LastServiceDate == null))
                {
                    Utility.ShowMessageBox(Message.MaintenanceTypeServicePeriodMileage);
                    ((IList)radMaintenanceRecord.ItemsSource).Remove(vmr);
                    e.Row.CancelEdit();
                    //vmr.LastServiceMileage = (int?)e.OldValues["LastServiceMileage"];
                    //vmr.LastServiceDate = (DateTime?)e.OldValues["LastServiceDate"];

                }
                else
                {
                    vmr.Operator = (string)Application.Current.Properties["CurrentUser"];
                    vrm.Update();
                    Utility.ShowMessageBox(Message.MaintenanceTypeSaveSucceed);
                }
            }
        }

        private void RadContextMenu_ItemClick(object sender, WiseLinkWPF.Windows.RadRoutedEventArgs e)
        {
            RadContextMenu menu = (RadContextMenu)sender;
            RadMenuItem clickedItem = e.OriginalSource as RadMenuItem;
            GridViewRow row = menu.GetClickedElement<GridViewRow>();

            //radMaintenanceRecord.SelectedItem = row;
            if (clickedItem != null && row != null)
            {
                if (clickedItem.Name == "Delete")
                {
                    if (row.Item == null) return;
                    ((IList)this.radMaintenanceRecord.ItemsSource).Remove(row.Item);
                    vrm.Update();
                }
            }
        }

        private void ApplyServiceDateMileage_Click(object sender, RoutedEventArgs e)
        {
            int? Mileage = Convert.ToInt32(this.LastServiceMileage.Value);
            DateTime? ServiceDate = this.LastServiceDate.SelectedDate;

            if ((Mileage == null) || (ServiceDate == null))
            {
                Utility.ShowMessageBox(Message.ServicePeriodMileageIsEmpty);
                return;
            }


            Device deviceData = this.radGridView1.CurrentItem as Device;
            if (deviceData == null) return;

            deviceData.Vehicle.LastServcieDate = ServiceDate;
            deviceData.Vehicle.LastServiceMileage = Mileage;
            deviceModel.Update();


            foreach (var r in radMaintenanceRecord.Items)
            {
                VehicleMaintenanceRecord mtd = r as VehicleMaintenanceRecord;
                if (mtd != null)
                {
                    mtd.LastServiceDate = ServiceDate;
                    mtd.LastServiceMileage = Mileage;
                }
            }
            vrm.Update();
        }

        private void radGridView1_CellValidating(object sender, GridViewCellValidatingEventArgs e)
        {
            // if there is no change of the value, no need to validate.
            if (e.NewValue == e.OldValue) return;
            GridViewCell cell = e.Cell;
            string validationText = string.Empty;

            switch (cell.Column.UniqueName)
            {
                case "MaintenanceType":
                    GridViewRow row = (GridViewRow)e.Cell.ParentRow;
                    int mtTypeId;
                    MaintenanceType mt;
                    if (Int32.TryParse(e.NewValue.ToString(), out mtTypeId))
                    {
                        Device deviceData = this.radGridView1.CurrentItem as Device;
                        if (mtTypeId == 0)
                        {
                            validationText = Message.MaintenanceTypeIsEmpty;
                        }
                        else
                        {
                            mt = vrm.GetMaintenanceType(mtTypeId);

                            if (!vrm.IsDuplicate(deviceData.VehicleID, mtTypeId, mt.Priority ?? 1))
                            {
                                ((VehicleMaintenanceRecord)row.DataContext).MaintenanceTypeID = mtTypeId;
                                ((VehicleMaintenanceRecord)row.DataContext).ServiceMileage = mt.ServiceMileage;
                                ((VehicleMaintenanceRecord)row.DataContext).ServicePeriod = mt.ServicePeriod;
                                ((VehicleMaintenanceRecord)row.DataContext).Priority = mt.Priority;
                                ((VehicleMaintenanceRecord)row.DataContext).AnchiID = mt.AnchiID;
                                vrm.Update();
                            }
                            else
                            {
                                validationText = Message.DuplicateMaintenanceType;
                                this.radMaintenanceRecord.CancelEdit();
                                Utility.ShowMessageBox(validationText);
                            }
                        }
                    }
                    else
                    {
                        validationText = "无法找到正确的保养项目";
                    }

                    break;
                default:
                    break;
            }
            if (!string.IsNullOrEmpty(validationText))
            {
                ToolTipService.SetToolTip(cell, validationText);
                e.IsValid = false;
                e.ErrorMessage = validationText;
            }
        }

        private List<Device> PagedData()
        {
            List<Device> printData = this.radDataPager1.Source.OfType<Device>().ToList();
            return printData;
        }

        private void radMaintenanceRecord_BeginningEdit(object sender, GridViewBeginningEditRoutedEventArgs e)
        {

            if (this.radMaintenanceRecord.Items.Count > 0)
            {
                e.Row.IsSelected = true;
                this.radMaintenanceRecord.SelectedItem = this.radMaintenanceRecord.Items[0];
            }
        }

        private void radMaintenanceRecord_CellValidated(object sender, GridViewCellValidatedEventArgs e)
        {
            if (e.ValidationResult.ErrorMessage != null)
            {
                this.radMaintenanceRecord.CancelEdit();
            }

        }

    }
}
